package com.kuqi;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.kuqi.ViewComponent.MineVideoView.MediaController;
import com.kuqi.ViewComponent.MineVideoView.VideoView;
import com.kuqi.ViewComponent.PullUpLoad.PullUpToLoadMore;
import com.kuqi.core.AppActivity;
import com.kuqi.entitiy.VideoItem;

public class MediaPlayerActivity extends AppActivity
        implements MediaController.onClickIsFullScreenListener, MediaController.onClickStartStopListener{

    // 整个视频的显示界面
    RelativeLayout rl_player;

    // 用来播放视频的控件对象
    VideoView mediaView;
    // 视频播放控件
    MediaController mediaController;
    // 当前正在播放的视频对象的信息
    VideoItem currentVideoInfo;

    // 视频正在加载中的图标
    private ImageView loading_signal;
    // 视频重播图标
    private ImageView replay_signal;

    // 提示含有详情的提示框
    private ImageView iv_tips_has_pre;
    private ImageView iv_tips_has_next;

    // 可以滑动的界面控件
    private PullUpToLoadMore pullUpToLoadMore;


    private VideoItem getParams(){
        Intent intent = this.getIntent();
        return (VideoItem)intent.getSerializableExtra("video_info");
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.video_player_page);

        // 隐藏顶部标题栏
        hideActionBar();
        //获取控件
        mediaView = findViewById(R.id.videoView);
        loading_signal = findViewById(R.id.loading_signal);
        replay_signal = findViewById(R.id.ending_signal);
        rl_player = findViewById(R.id.rl_player);
        iv_tips_has_pre = findViewById(R.id.iv_tips_has_pre);
        iv_tips_has_next = findViewById(R.id.iv_tips_has_next);
        pullUpToLoadMore = findViewById(R.id.load_more_group);

        // 测量并设置播放窗体的样式（与全屏与否有关）
        checkAndMeasurePlayerSize();

        // 设置等待的图标为一个加载ing的gif
        Glide.with(this).asGif().load(R.mipmap.video_loading_gif).into(loading_signal);

        //取出传递来的视频
        currentVideoInfo = this.getParams();
        // 显示视频详情
        setVideoInfoShown(currentVideoInfo);
        //为播放器添加控制器，因为开放的自定义接口存在大量问题，不适用
        mediaController = new MediaController(this);
        mediaView.setMediaController(mediaController);

        // 设置全屏按钮监听（自定义）
        mediaController.setClickIsFullScreenListener(this);
        // 设置开始暂停按钮监听（自定义）
        mediaController.setClickStartStopListener(this);

        // 设置重播按钮功能
        replay_signal.setOnClickListener(replayListener);

        // 拖动加载控制器
        pullUpToLoadMore.setPullIndexListener(detailsIndexListener);

        // 设置视频路径并开始播放
        Log.e("读取视频：", currentVideoInfo.getAddress());
        mediaView.setVideoURI(Uri.parse(currentVideoInfo.getAddress()));
        mediaView.setOnPreparedListener(videoPrepared);
        mediaView.setOnCompletionListener(videoCompletion);
        mediaController.hide();
    }

    @Override
    protected void onDestroy() {
        // 注意，在切换横竖屏时，页面会注销并重新加载。
        // 如果不将播放器销毁，则会造成泄露
        mediaController.hide();
        mediaView.stopPlayback();
        super.onDestroy();
    }

    /**
     * 在视频下方展现相应的介绍和注释
     * @param info 对应的视频信息
     */
    private void setVideoInfoShown(VideoItem info)
    {
        TextView video_technology = findViewById(R.id.video_technology);
        video_technology.setText(info.getTechnology());
        TextView video_assessment = findViewById(R.id.video_assessment);
        video_assessment.setText(info.getAssessment());
        TextView video_particulars = findViewById(R.id.video_particulars);
        video_particulars.setText(info.getParticulars());
    }

    /**
     * 当视频加载完成后执行
     */
    MediaPlayer.OnPreparedListener videoPrepared = new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            loading_signal.setVisibility(View.GONE);
            mediaView.requestFocus();
            mediaView.start();
        }
    };

    /**
     * 当视频播放结束的时候
     */
    MediaPlayer.OnCompletionListener videoCompletion = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            replay_signal.setVisibility(View.VISIBLE);
        }
    };


    /**
     * 点击全屏时应有的处理方案
     * // TODO 全屏功能有些bug，暂时禁用全屏
     */
    @SuppressLint("SourceLockedOrientationActivity")
    public void setOnClickIsFullScreen() {
        Log.e("videoPlayer","全屏功能暂时禁用");
//        if(this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
//            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); // 横向
//        }else{
//            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //纵向
//        }
    }

    /**
     * 这里是个临时的不优秀的方案
     * 当横竖屏切换时，页面会重新加载
     * 为了保证切换后显示界面符合全屏，需要重新测量并修改布局
     */
    private void checkAndMeasurePlayerSize(){
        if(this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
            RelativeLayout.LayoutParams contentParam = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.MATCH_PARENT,RelativeLayout.LayoutParams.MATCH_PARENT);
            // 这里将200的pix单位转为dp
            int heightDP = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, getResources().getDisplayMetrics());;
            contentParam.height = heightDP;
            rl_player.setLayoutParams(contentParam);
        }else{
            RelativeLayout.LayoutParams contentParam = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.MATCH_PARENT,RelativeLayout.LayoutParams.MATCH_PARENT);
            rl_player.setLayoutParams(contentParam);
        }
    }


    /**
     * 单击控制栏上的开始暂停按钮
     * (对播放器内部的功能已经封装实现，这里开放只为外部界面的修改)
     */
    @Override
    public void setOnClickStartStop() {
        // 如果你点击了控制栏上的按钮，那页面上的控制就必须隐藏
        replay_signal.setVisibility(View.GONE);
        loading_signal.setVisibility(View.GONE);
    }


    /**
     * 单击播放接受后的重播按钮功能
     */
    ImageView.OnClickListener replayListener = new ImageView.OnClickListener(){
        @Override
        public void onClick(View v) {
            replay_signal.setVisibility(View.GONE);
            if(mediaView.isPlaying()){
                mediaView.stopPlayback();
            }
            mediaView.start();
        }
    };


    /**
     * 当详情条目翻页时触发回调
     */
    PullUpToLoadMore.PullIndexListener detailsIndexListener = new PullUpToLoadMore.PullIndexListener() {
        @Override
        public void reachFirst() {
        }

        @Override
        public void reachEnd() {
        }

        @Override
        public void currentChanged(int currentIndex, boolean isFirst, boolean isEnd) {
            if(isFirst){
                iv_tips_has_next.setVisibility(View.VISIBLE);
            }else{
                iv_tips_has_next.setVisibility(View.GONE);
            }
        }
    };

}
